const router = require("express").Router();
const sql = require("../mysql");
const Ticket = require("../mysql/collection/Ticket");
const uuid = require("uuid");

/**
 * @api {GET} /admin/crm/tickets 获取工单列表
 * @apiName GetTickets
 * @apiGroup CRM-Ticket
 *
 * @apiParam {Number} [page=1] 页码
 * @apiParam {Number} [pageSize=10] 每页数量
 * @apiParam {String} [status] 工单状态筛选
 * @apiParam {String} [priority] 优先级筛选
 * @apiParam {String} [category] 工单类别筛选
 * @apiParam {String} [assignedTo] 负责人筛选
 * @apiParam {String} [keyword] 关键词搜索(标题、描述)
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 数据
 * @apiSuccess {Array} data.list 工单列表
 * @apiSuccess {Number} data.total 总数
 * @apiSuccess {Number} data.page 当前页
 * @apiSuccess {Number} data.pageSize 每页数量
 */
router.get("/tickets", async (req, res) => {
  try {
    const { page = 1, pageSize = 10, status, priority, category, assignedTo, keyword } = req.query;
    const skip = (page - 1) * pageSize;
    
    // 构建查询条件
    let query = {};
    if (status) query.status = status;
    if (priority) query.priority = priority;
    if (category) query.category = category;
    if (assignedTo) query.assignedTo = assignedTo;
    if (keyword) {
      query.$or = [
        { title: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } }
      ];
    }
    
    const total = await Ticket.countDocuments(query);
    const list = await Ticket.find(query)
      .populate('customerId', 'name company phone')
      .populate('assignedTo', 'adminname')
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(pageSize));
    
    res.send({
      code: "200",
      message: "获取工单列表成功",
      data: {
        list,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取工单列表失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/tickets 创建工单
 * @apiName CreateTicket
 * @apiGroup CRM-Ticket
 *
 * @apiParam {String} customerId 客户ID
 * @apiParam {String} title 工单标题
 * @apiParam {String} description 工单描述
 * @apiParam {String} [priority] 优先级
 * @apiParam {String} [category] 工单类别
 * @apiParam {String} [assignedTo] 分配给客服代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 工单数据
 */
router.post("/tickets", async (req, res) => {
  try {
    const ticketData = {
      ...req.body,
      ticketId: "TKT_" + uuid.v4().replace(/-/g, '').substring(0, 12).toUpperCase()
    };
    
    const ticket = await Ticket.create(ticketData);
    const populatedTicket = await Ticket.findById(ticket._id)
      .populate('customerId', 'name company phone')
      .populate('assignedTo', 'adminname');
    
    res.send({
      code: "200",
      message: "创建工单成功",
      data: populatedTicket
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "创建工单失败",
      error: error.message
    });
  }
});

/**
 * @api {GET} /admin/crm/tickets/:id 获取工单详情
 * @apiName GetTicketDetail
 * @apiGroup CRM-Ticket
 *
 * @apiParam {String} id 工单ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 工单详情
 */
router.get("/tickets/:id", async (req, res) => {
  try {
    const ticket = await Ticket.findById(req.params.id)
      .populate('customerId', 'name company phone')
      .populate('assignedTo', 'adminname');
    
    if (!ticket) {
      return res.send({
        code: "404",
        message: "工单不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "获取工单详情成功",
      data: ticket
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "获取工单详情失败",
      error: error.message
    });
  }
});

/**
 * @api {PUT} /admin/crm/tickets/:id 更新工单信息
 * @apiName UpdateTicket
 * @apiGroup CRM-Ticket
 *
 * @apiParam {String} id 工单ID
 * @apiParam {String} [title] 工单标题
 * @apiParam {String} [description] 工单描述
 * @apiParam {String} [priority] 优先级
 * @apiParam {String} [category] 工单类别
 * @apiParam {String} [status] 工单状态
 * @apiParam {String} [assignedTo] 分配给客服代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 更新后的工单数据
 */
router.put("/tickets/:id", async (req, res) => {
  try {
    const ticket = await Ticket.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    ).populate('customerId', 'name company phone')
     .populate('assignedTo', 'adminname');
    
    if (!ticket) {
      return res.send({
        code: "404",
        message: "工单不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "更新工单信息成功",
      data: ticket
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "更新工单信息失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/tickets/:id/assign 分配工单
 * @apiName AssignTicket
 * @apiGroup CRM-Ticket
 *
 * @apiParam {String} id 工单ID
 * @apiParam {String} assignedTo 分配给客服代表ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 分配后的工单数据
 */
router.post("/tickets/:id/assign", async (req, res) => {
  try {
    const { assignedTo } = req.body;
    
    const ticket = await Ticket.findByIdAndUpdate(
      req.params.id,
      { 
        assignedTo,
        status: '处理中'
      },
      { new: true }
    ).populate('customerId', 'name company phone')
     .populate('assignedTo', 'adminname');
    
    if (!ticket) {
      return res.send({
        code: "404",
        message: "工单不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "分配工单成功",
      data: ticket
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "分配工单失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/tickets/:id/resolve 解决工单
 * @apiName ResolveTicket
 * @apiGroup CRM-Ticket
 *
 * @apiParam {String} id 工单ID
 * @apiParam {String} [solution] 解决方案
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 解决后的工单数据
 */
router.post("/tickets/:id/resolve", async (req, res) => {
  try {
    const { solution } = req.body;
    
    const ticket = await Ticket.findByIdAndUpdate(
      req.params.id,
      { 
        status: '已解决',
        solution: solution || '',
        resolveTime: new Date()
      },
      { new: true }
    ).populate('customerId', 'name company phone')
     .populate('assignedTo', 'adminname');
    
    if (!ticket) {
      return res.send({
        code: "404",
        message: "工单不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "工单解决成功",
      data: ticket
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "工单解决失败",
      error: error.message
    });
  }
});

/**
 * @api {POST} /admin/crm/tickets/:id/close 关闭工单
 * @apiName CloseTicket
 * @apiGroup CRM-Ticket
 *
 * @apiParam {String} id 工单ID
 * @apiParam {String} [closeReason] 关闭原因
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 * @apiSuccess {Object} data 关闭后的工单数据
 */
router.post("/tickets/:id/close", async (req, res) => {
  try {
    const { closeReason } = req.body;
    
    const ticket = await Ticket.findByIdAndUpdate(
      req.params.id,
      { 
        status: '已关闭',
        closeReason: closeReason || '',
        resolveTime: new Date()
      },
      { new: true }
    ).populate('customerId', 'name company phone')
     .populate('assignedTo', 'adminname');
    
    if (!ticket) {
      return res.send({
        code: "404",
        message: "工单不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "工单关闭成功",
      data: ticket
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "工单关闭失败",
      error: error.message
    });
  }
});

/**
 * @api {DELETE} /admin/crm/tickets/:id 删除工单
 * @apiName DeleteTicket
 * @apiGroup CRM-Ticket
 *
 * @apiParam {String} id 工单ID
 *
 * @apiHeader {String} token 认证令牌
 *
 * @apiSuccess {String} code 状态码
 * @apiSuccess {String} message 描述
 */
router.delete("/tickets/:id", async (req, res) => {
  try {
    const ticket = await Ticket.findByIdAndDelete(req.params.id);
    
    if (!ticket) {
      return res.send({
        code: "404",
        message: "工单不存在"
      });
    }
    
    res.send({
      code: "200",
      message: "删除工单成功"
    });
  } catch (error) {
    res.send({
      code: "500",
      message: "删除工单失败",
      error: error.message
    });
  }
});

module.exports = router;